package ManHinhChinh;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.ModifyEvent;

public class DatHang {

	protected Shell DatHang;
	private Text txt_MaDDH;
	private Text txt_Soluong;
	private Table table;
	private Text txt_DonGia;
	private Text txt_DVTinh;
	private Combo cbMatHang;
	private Combo cbTenKH;
	private boolean started;
	Composite composite;
	Composite composite_1;
	Button btn_DH_Them;
	Button btn_DH_Ghi;
	DateTime dateTimeNgayDat;
	DateTime dateTimeNgayNhan;

	String sSelectfromKH = "select * from KHACH_HANG"; // lấy thông tin nhà cung
														// cấp
	String sSelectfromHH = "select * from HANG_HOA"; // lấy thông tin hàng hóa
	String sSelectfromDDH = "select * from DON_DAT_HANG";// lấy thông tin phiếu
	private Text txt_TongTien;
															// nhập hàng

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		// canh giua man hinh
		Monitor primary = display.getPrimaryMonitor();
		Rectangle bounds = primary.getBounds();
		Rectangle rect = DatHang.getBounds();
		int x = bounds.x + (bounds.width - rect.width) / 2;
		int y = bounds.y + (bounds.height - rect.height) / 2;
		DatHang.setLocation(x, y);

		DatHang.open();
		DatHang.layout();
		while (!DatHang.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}

	/**
	 * Create contents of the window.
	 * 
	 * @wbp.parser.entryPoint
	 */
	protected void createContents() {
		DatHang = new Shell();
		DatHang.addShellListener(new ShellAdapter() {
			@Override
			public void shellActivated(ShellEvent e) {
				// lần đầu tiên: started = false -> sau lần đầu tiên started =
				// true
				if (!started) {
					DatHang.setVisible(true);
					TaoKetNoi kn = new TaoKetNoi();
					Connection con = kn.TaoLienKet();

					Statement stm = null;
					ResultSet rs = null;
					DataUser _du = new DataUser();
					// hiển thị mã phiếu nhập hàng tự động
					txt_MaDDH.setText(_du.taoMaDatHang());
					try {
						stm = con.createStatement();
						rs = stm.executeQuery(sSelectfromKH);
						while (rs.next()) {
							String key1 = rs.getString("HOTEN");
							cbTenKH.add(key1);
							cbTenKH.setData(key1, rs.getString("MAKHACHHANG"));
						}
						rs = stm.executeQuery(sSelectfromHH);
						while (rs.next()) {
							String key2 = rs.getString("TENHANGHOA");
							cbMatHang.add(key2);
							cbMatHang.setData(key2, rs.getString("MAHANGHOA"));
						}
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} finally {
						try {
							stm.close();
							rs.close();
							con.close();
						} catch (SQLException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
					capnhatTable();
					started = true;
				}
			}
		});
		DatHang.setSize(690, 577);
		DatHang.setText("\u0110\u1EB7t H\u00E0ng");

		composite = new Composite(DatHang, SWT.NONE);
		composite.setBounds(10, 25, 656, 151);

		Label lblNewLabel = new Label(composite, SWT.NONE);
		lblNewLabel.setFont(SWTResourceManager.getFont("Times New Roman", 12,
				SWT.NORMAL));
		lblNewLabel.setBounds(27, 10, 104, 21);
		lblNewLabel.setText("Mã đơn đặt hàng");

		Label lblNewLabel_1 = new Label(composite, SWT.NONE);
		lblNewLabel_1.setFont(SWTResourceManager.getFont("Times New Roman", 12,
				SWT.NORMAL));
		lblNewLabel_1.setBounds(27, 55, 115, 21);
		lblNewLabel_1.setText("Tên Khách Hàng");

		txt_MaDDH = new Text(composite, SWT.BORDER);
		txt_MaDDH.setBounds(148, 10, 174, 21);

		//button DAT HANG
		Button btnDatHang = new Button(composite, SWT.NONE);
		btnDatHang.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (txt_MaDDH.getText().equals("")) {
					MessageBox mb = new MessageBox(DatHang, SWT.ICON_ERROR
							| SWT.OK);
					mb.setText("Error");
					mb.setMessage("Bạn chưa nhập Mã hóa đơn nhập.");
					mb.open();
					txt_MaDDH.forceFocus();
					return;
				}

				if (cbTenKH.getText().equals("")) {
					MessageBox mb = new MessageBox(DatHang, SWT.ICON_ERROR
							| SWT.OK);
					mb.setText("Error");
					mb.setMessage("Bạn chưa chọn khách hàng.");
					mb.open();
					cbTenKH.forceFocus();
					return;
				}

				TaoKetNoi kn = new TaoKetNoi();
				Connection con = kn.TaoLienKet();
				//Kiểm tra mã phiếu nhập	
				try {
					Statement stm = con.createStatement();
					ResultSet rs = stm.executeQuery(sSelectfromDDH);
					while (rs.next()) {
						if (txt_MaDDH.getText().equals(
								rs.getString("MAPNH").trim())) {
							MessageBox ms = new MessageBox(DatHang, SWT.ERROR
									| SWT.OK);
							ms.setText("Error");
							ms.setMessage("Mã đơn đặt hàng đã tồn tại.");
							ms.open();
							return;
						}
					}
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} 
				
				// INSERT thông tin phiếu nhập vào csdl DON_DAT_HANG
				PreparedStatement pstm;
				String sInsertPNH = "Insert into DON_DAT_HANG values(?,?,?,?, 0)";
				String MaKh = (String)cbTenKH.getData(cbTenKH.getText()).toString().trim();
				String Ngaydathang = dateTimeNgayDat.toString().substring(10, dateTimeNgayDat.toString().length()-1);
				String Ngaynhanhang = dateTimeNgayNhan.toString().substring(10, dateTimeNgayNhan.toString().length()-1);
				try {
					pstm = con.prepareStatement(sInsertPNH);
					pstm.setString(1, MaKh);
					pstm.setString(2, txt_MaDDH.getText().trim());
					pstm.setString(3, Ngaydathang );
					pstm.setString(4, Ngaynhanhang);
					pstm.executeUpdate();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					MessageBox mb = new MessageBox (DatHang, SWT.ERROR);
					mb.setText("Database Error");
					mb.setMessage(e1.getMessage());
					mb.open();
					return;
				}
				
				

				// enable khung nhap hang hoa phia duoi
				// disable khung nhap hoa don phia tren
				composite.setEnabled(false);
				composite_1.setEnabled(true);

				// Enable mot so nut
				btn_DH_Ghi.setEnabled(true);
				btn_DH_Them.setEnabled(true);
				//btn_NH_Hoan.setEnabled(true);
			}
			
		});
		btnDatHang.setImage(SWTResourceManager
				.getImage("..\\_QuanLyBanHang\\image\\text.ico"));
		btnDatHang.setBounds(287, 106, 115, 35);
		btnDatHang.setText("\u0110\u1EB7t H\u00E0ng");

		cbTenKH = new Combo(composite, SWT.NONE | SWT.READ_ONLY);
		cbTenKH.setBounds(148, 55, 174, 23);

		Label lblNewLabel_5 = new Label(composite, SWT.NONE);
		lblNewLabel_5.setBounds(392, 18, 76, 18);
		lblNewLabel_5.setFont(SWTResourceManager.getFont("Times New Roman", 12,
				SWT.NORMAL));
		lblNewLabel_5.setText("Ng\u00E0y \u0110\u1EB7t");

		dateTimeNgayDat = new DateTime(composite, SWT.BORDER);
		dateTimeNgayDat.setBounds(501, 10, 111, 24);

		Label lblNewLabel_7 = new Label(composite, SWT.NONE);
		lblNewLabel_7.setBounds(392, 57, 76, 21);
		lblNewLabel_7.setFont(SWTResourceManager.getFont("Times New Roman", 12,
				SWT.NORMAL));
		lblNewLabel_7.setText("Ng\u00E0y Nh\u1EADn");

		dateTimeNgayNhan = new DateTime(composite, SWT.BORDER);
		dateTimeNgayNhan.setBounds(501, 54, 111, 24);

		composite_1 = new Composite(DatHang, SWT.NONE);
		composite_1.setBounds(10, 201, 654, 123);
		composite_1.setEnabled(false);

		Label lblNewLabel_4 = new Label(composite_1, SWT.NONE);
		lblNewLabel_4.setFont(SWTResourceManager.getFont("Times New Roman", 12,
				SWT.NORMAL));
		lblNewLabel_4.setBounds(32, 10, 76, 21);
		lblNewLabel_4.setText("M\u1EB7t H\u00E0ng");

		Label lblNewLabel_6 = new Label(composite_1, SWT.NONE);
		lblNewLabel_6.setFont(SWTResourceManager.getFont("Times New Roman", 12,
				SWT.NORMAL));
		lblNewLabel_6.setBounds(32, 57, 76, 21);
		lblNewLabel_6.setText("S\u1ED1 L\u01B0\u1EE3ng");

		txt_Soluong = new Text(composite_1, SWT.BORDER);
		txt_Soluong.setBounds(114, 57, 165, 21);

		cbMatHang = new Combo(composite_1, SWT.NONE | SWT.READ_ONLY);
		cbMatHang.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent arg0) {
				TaoKetNoi kn = new TaoKetNoi();
				Connection con = kn.TaoLienKet();
				PreparedStatement pstm = null;
				ResultSet rs = null;

				try {
					String sql = "Select * from HANG_HOA where TENHANGHOA = ?";
					pstm = con.prepareStatement(sql);
					pstm.setString(1, cbMatHang.getText());
					rs = pstm.executeQuery();
					while (rs.next()) {
						txt_DVTinh.setText(rs.getNString("DONVITINH"));
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				finally {
					try {
						pstm.close();
						rs.close();
						con.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		cbMatHang.setBounds(114, 10, 165, 23);

		Label lblonGi = new Label(composite_1, SWT.NONE);
		lblonGi.setText("Đơn giá");
		lblonGi.setFont(SWTResourceManager.getFont("Times New Roman", 12,
				SWT.NORMAL));
		lblonGi.setBounds(351, 57, 76, 21);

		txt_DonGia = new Text(composite_1, SWT.BORDER);
		txt_DonGia.setBounds(435, 57, 190, 21);

		txt_DVTinh = new Text(composite_1, SWT.BORDER|SWT.READ_ONLY);
		txt_DVTinh.setBounds(435, 10, 190, 21);

		Label lblnVTnh = new Label(composite_1, SWT.NONE);
		lblnVTnh.setText("Đơn vị tính");
		lblnVTnh.setFont(SWTResourceManager.getFont("Times New Roman", 12,
				SWT.NORMAL));
		lblnVTnh.setBounds(335, 10, 76, 21);
		
		Label lblTngTin = new Label(composite_1, SWT.NONE);
		lblTngTin.setText("Tổng tiền");
		lblTngTin.setFont(SWTResourceManager.getFont("Times New Roman", 12, SWT.NORMAL));
		lblTngTin.setBounds(167, 92, 76, 21);
		
		txt_TongTien = new Text(composite_1, SWT.BORDER | SWT.READ_ONLY);
		txt_TongTien.setBounds(249, 92, 165, 21);

		btn_DH_Them = new Button(DatHang, SWT.NONE);
		btn_DH_Them.setImage(SWTResourceManager
				.getImage("..\\_QuanLyBanHang\\image\\ADD.ICO"));
		btn_DH_Them.setBounds(10, 503, 75, 25);
		btn_DH_Them.setText("Thêm");
		btn_DH_Them.setEnabled(false);
		
		//button GHI
		btn_DH_Ghi = new Button(DatHang, SWT.NONE);
		btn_DH_Ghi.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (cbMatHang.getText() == "") {
					MessageBox mb = new MessageBox(DatHang, SWT.ICON_ERROR
							| SWT.OK);
					mb.setText("Error");
					mb.setMessage("Bạn chưa chọn mặt hàng.");
					mb.open();
					cbMatHang.forceFocus();
					return;
				}

				if (txt_Soluong.getText() == "") {
					MessageBox mb = new MessageBox(DatHang, SWT.ICON_ERROR
							| SWT.OK);
					mb.setText("Error");
					mb.setMessage("Bạn chưa nhập số lượng.");
					mb.open();
					txt_Soluong.forceFocus();
					return;
				}


				if (txt_DonGia.getText() == "") {
					MessageBox mb = new MessageBox(DatHang, SWT.ICON_ERROR
							| SWT.OK);
					mb.setText("Error");
					mb.setMessage("Bạn chưa nhập đơn giá.");
					mb.open();
					txt_DonGia.forceFocus();
					return;
				}

				// Update csdl
				// thêm vào bảng chi tiết phiếu nhập
				TaoKetNoi kn = new TaoKetNoi();
				Connection con = kn.TaoLienKet();
				PreparedStatement pstm;
				String sInsertCTPNH = "insert into CHI_TIET_DDH values(?,?,?,?,?,?)";
				String MaKh = (String) cbTenKH.getData(cbTenKH.getText())
						.toString().trim();
				String MaHH = (String) cbMatHang.getData(cbMatHang.getText())
						.toString().trim();
				int sluong = Integer.parseInt(txt_Soluong.getText().trim());
				int dongia = Integer.parseInt(txt_DonGia.getText()
						.trim());
				try {
					pstm = con.prepareStatement(sInsertCTPNH);
					pstm.setString(1, MaKh);
					pstm.setString(2, txt_MaDDH.getText().trim());
					pstm.setString(3, MaHH);
					pstm.setInt(4, sluong);
					pstm.setInt(5, dongia);
					pstm.setInt(6, sluong * dongia);
					pstm.executeUpdate();

					// Cập nhật lại Số Lượng cho bảng HANG_HOA (thêm số lượng
					// mặt hàng)
					// String updatesoluong =
					// "update HANG_HOA set SOLUONGTON = SOLUONGTON + ? , DONGIADENGHI = ? where MAHANGHOA = ?";
					// PreparedStatement pStm2 =
					// con.prepareStatement(updatesoluong);
					// pStm2.setInt(1, slTonduocnhap);
					// pStm2.setInt(2, dongia);
					// pStm2.setString(3, MaHH);
					// pStm2.executeUpdate();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					MessageBox mb = new MessageBox (DatHang, SWT.ERROR);
					mb.setText("Database Error");
					mb.setMessage(e1.getMessage());
					mb.open();
					return;
				}

				try {
					con.close();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				capnhatTable();
				tinhTongtien();
				MessageBox ms = new MessageBox(DatHang, SWT.OK);
				ms.setText("");
				ms.setMessage("Đã lưu.");
				ms.open();

			}
		});
		btn_DH_Ghi.setImage(SWTResourceManager
				.getImage("..\\_QuanLyBanHang\\image\\Save.ico"));
		btn_DH_Ghi.setText("Ghi");
		btn_DH_Ghi.setBounds(300, 503, 75, 25);
		btn_DH_Ghi.setEnabled(false);

		Button btn_DH_thoat = new Button(DatHang, SWT.NONE);
		btn_DH_thoat.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				DatHang.close();
			}
		});
		btn_DH_thoat.setImage(SWTResourceManager
				.getImage("..\\_QuanLyBanHang\\image\\exit.ico"));
		btn_DH_thoat.setText("Tho\u00E1t");
		btn_DH_thoat.setBounds(591, 503, 75, 25);

		table = new Table(DatHang, SWT.BORDER | SWT.FULL_SELECTION
				| SWT.VIRTUAL);
		table.setLinesVisible(true);
		table.setItemCount(1);
		table.setHeaderVisible(true);
		table.setBackground(SWTResourceManager
				.getColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
		table.setBounds(10, 330, 656, 136);

		TableColumn tableColumn = new TableColumn(table, SWT.CENTER);
		tableColumn.setWidth(68);
		tableColumn.setText("Số thứ tự");

		TableColumn tableColumn_1 = new TableColumn(table, SWT.CENTER);
		tableColumn_1.setWidth(81);
		tableColumn_1.setText("Mã mặt hàng");

		TableColumn tableColumn_2 = new TableColumn(table, SWT.CENTER);
		tableColumn_2.setWidth(100);
		tableColumn_2.setText("Tên mặt hàng");

		TableColumn tableColumn_3 = new TableColumn(table, SWT.CENTER);
		tableColumn_3.setWidth(100);
		tableColumn_3.setText("Đơn vị tính");

		TableColumn tableColumn_4 = new TableColumn(table, SWT.CENTER);
		tableColumn_4.setWidth(100);
		tableColumn_4.setText("Số lượng");

		TableColumn tblclmnnGiBn = new TableColumn(table, SWT.CENTER);
		tblclmnnGiBn.setWidth(100);
		tblclmnnGiBn.setText("Đơn giá bán");

		TableColumn tableColumn_6 = new TableColumn(table, SWT.CENTER);
		tableColumn_6.setWidth(100);
		tableColumn_6.setText("Thành tiền");
		
		// /////////////////////////////////////////////////////////////////////////
		// phải chuột để xóa item trong table
		// /////////////////////////////////////////////////////////////////////////
		Menu menu = new Menu(DatHang, SWT.POP_UP);
		table.setMenu(menu);
		MenuItem mitem = new MenuItem(menu, SWT.PUSH);
		mitem.setText("Xóa");
		mitem.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event event) {
				table.remove(table.getSelectionIndices());
				String MaHH = (String) cbMatHang.getData(cbMatHang.getText())
						.toString().trim();
				String delete = "Delete from CHI_TIET_DDH where (MADONDATHANG = ?) and (MAHANGHOA = ?) ";
				TaoKetNoi s = new TaoKetNoi();
				Connection con = s.TaoLienKet();
				try {
					PreparedStatement pStm = con.prepareStatement(delete);
					pStm.setString(1, txt_MaDDH.getText().trim());
					pStm.setString(2, MaHH);
					pStm.executeUpdate();
					con.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				capnhatTable();
				tinhTongtien();
			}
		});

	}
	
	public void capnhatTable() {
		table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
		table.setItemCount(0);
		TaoKetNoi s = new TaoKetNoi();
		Connection con = s.TaoLienKet();
		int stt = 1;
		try {
			PreparedStatement pstm = con
					.prepareStatement("Select CHI_TIET_DDH.MAHANGHOA, TENHANGHOA, DONVITINH, SOLUONG, DONGIA, THANHTIEN"
							+ " from CHI_TIET_DDH inner join HANG_HOA on CHI_TIET_DDH.MAHANGHOA = HANG_HOA.MAHANGHOA"
							+ " where MADONDATHANG = ?");
			pstm.setString(1, txt_MaDDH.getText().trim());
			ResultSet resultSet = pstm.executeQuery();
			while (resultSet.next()) {

				TableItem item = new TableItem(table, SWT.NONE);
				item.setText(new String[] { Integer.toString(stt),
						resultSet.getString("MAHANGHOA"),
						resultSet.getString("TENHANGHOA"),
						resultSet.getString("DONVITINH"),
						resultSet.getString("SOLUONG"),
						resultSet.getString("DONGIA"),
						resultSet.getString("THANHTIEN") });
				stt++;
			}
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void tinhTongtien()
	{
		TaoKetNoi s = new TaoKetNoi();
		Connection con = s.TaoLienKet();
		double tongtien = 0;
		try {
			PreparedStatement pStm = con.prepareStatement("select TONGTIEN from DON_DAT_HANG where MADONDATHANG = ?");
			pStm.setString(1,txt_MaDDH.getText().trim());
			ResultSet rs = pStm.executeQuery();
			while(rs.next())
			{
				tongtien = rs.getDouble("TONGTIEN");
			}
			txt_TongTien.setText(Double.toString(tongtien));
//			pStm = con.prepareStatement("update HANG_HOA set TONGTIENPNH = ?");
//			pStm.setDouble(1, tongtien);
//			pStm.executeUpdate();
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
